package com.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.common.context.UserContextHolder;
import com.common.properties.SecurityProperties;
import com.common.tool.JwtTool;
import com.common.tool.ResponseTool;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private SecurityProperties securityProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(securityProperties.getAuthentication().getAccess_name());
        if (!StrUtil.isEmptyIfStr(token)) {
            Long id = JwtTool.getId(token, securityProperties.getAuthentication().getAccess_secretKey());
            UserContextHolder.getContext().setUsersToken(token);
            UserContextHolder.getContext().setUsersId(id);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.clear();
    }
}
